import { BAIDU_TOKEN_URL, TTS_URL } from "@/config/static.ts";
import { API_KEY, API_SECRET, FY_API_ID, FY_API_SECRET } from "@/config/pwd.ts";
import qs from "qs";
import { MD5 } from "crypto-js";

/**
 * BaiduHandler
 */
class BaiduHandler {
  readonly baiduTokenUrl: string;
  readonly ttsUrl: string;

  private token: string;
  private readonly apiKey: string;
  private readonly apiSecret: string;

  // private readonly _this: BaiduHandler;

  constructor(apiKey?: string, apiSecret?: string) {
    this.baiduTokenUrl = BAIDU_TOKEN_URL;
    this.ttsUrl = TTS_URL;
    this.token = "";
    this.apiKey = apiKey || API_KEY;
    this.apiSecret = apiSecret || API_SECRET;
    //更新token
    this.fetchToken();
  }

  public getAudio = (msg: string) => {
    return fetch("/audio/text2audio", {
      method: "POST",
      body: qs.stringify({
        tex: msg,
        tok: this.token,
        cuid: "masaikkmasaikk",
        ctp: "1",
        lan: "zh",
        spd: "5",
        pit: "5",
        vol: "5",
        per: "0",
        aue: "6",
      }),
    });
  };

  public fetchToken = (): void => {
    fetch("/api/oauth/2.0/token", {
      method: "POST",
      headers: {
        "Content-Type": "application/json; charset=utf-8",
      },
      body: qs.stringify({
        client_id: this.apiKey,
        client_secret: this.apiSecret,
        grant_type: "client_credentials",
      }),
    })
      .then((response) => response.json())
      .then((result) => {
        this.token = result.refresh_token;
        // 刷新token
      })
      .catch((error) => {
        console.error("Error:", error);
      });
  };

  public fetchAndPlayAudio = (msg: string): void => {
    this.getAudio(msg)
      .then((response) => {
        if (response.ok) {
          return response.blob();
        }
        throw new Error("Network response was not ok.");
      })
      .then((blob) => {
        const audioUrl = URL.createObjectURL(blob);
        const audio = new Audio(audioUrl);
        audio.play();
      })
      .catch((error) => {
        console.error("Error fetching TTS audio:", error);
        this.fetchToken();
      });
  };

  public getMD5 = (msg: string): string => {
    return MD5(msg).toString();
  };

  public translateWywFetch = (message: string) => {
    const salt: string = "114514";
    const toMD5: string = FY_API_ID + message + salt + FY_API_SECRET;
    const md5Str: string = this.getMD5(toMD5);

    const params = {
      q: message,
      from: "wyw",
      to: "zh",
      appid: FY_API_ID,
      salt: salt,
      sign: md5Str,
    };

    // console.log(params);

    const url = new URL("/trans", window.location.origin);
    url.search = new URLSearchParams(params).toString();
    return fetch(url, {
      method: "GET",
    });
  };

  public translate = async (msg: string) => {
    try {
      const response = await this.translateWywFetch(msg);
      const data = await response.json();
      // console.log(data);
      return data.trans_result[0].dst;
    } catch (error) {
      console.error(error);
    }
  };
}

export { BaiduHandler };
